﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Net.Mime;
using Helpers;

namespace Helpers
{
    /// <summary>
    /// http帮助类，需要类库System.Net.Http
    /// </summary>
    public class HttpHelper
    {
        public static HttpHelper Instance = new HttpHelper();

        public HttpClient httpClient = new HttpClient();

        public WebClient webclient = new WebClient();
        public string BaseAddress { set { httpClient.BaseAddress = new Uri(value); } }
        public void SetHttpClient(List<KeyValuePair<string, string>> arr)
        {
            if (arr != null)
                foreach (var item in arr)
                {
                    httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            httpClient.DefaultRequestHeaders.ExpectContinue = false;
        }

        public void AddHeader(HeaderType key, string value)
        {
            httpClient.DefaultRequestHeaders.Add(key.GetEnumDescription(), value);
            httpClient.DefaultRequestHeaders.ExpectContinue = false;
        }
        public string Get(string uri, string encoding = "utf-8")
        {
            HttpResponseMessage response = httpClient.GetAsync(uri).Result;
            response.EnsureSuccessStatusCode();
            return Encoding.GetEncoding(encoding).GetString(response.Content.ReadAsByteArrayAsync().Result);
        }

        public byte[] GetByte(string uri)
        {
            HttpResponseMessage response = httpClient.GetAsync(uri).Result;
            response.EnsureSuccessStatusCode();
            return response.Content.ReadAsByteArrayAsync().Result;
        }
        public string Post(string uri, string json, string encoding = "utf-8", string mediaType = "application/json")
        {
            HttpContent httpContent = new StringContent(json, Encoding.GetEncoding(encoding), mediaType);
            HttpResponseMessage response = httpClient.PostAsync(uri, httpContent).Result;
            response.EnsureSuccessStatusCode();
            return response.Content.ReadAsStringAsync().Result;
        }

        public string Post(string uri, List<KeyValuePair<String, String>> paramList, string encoding = "utf-8")
        {
            HttpResponseMessage response = httpClient.PostAsync(uri, new FormUrlEncodedContent(paramList)).Result;
            response.EnsureSuccessStatusCode();
            return Encoding.GetEncoding(encoding).GetString(response.Content.ReadAsByteArrayAsync().Result);
        }

        /// <summary>
        /// 设置cookie
        /// </summary>
        /// <param name="cookie">cookie字符串</param>
        /// <param name="domain">主机</param>
        public void SetCookie(string cookie, string domain)
        {
            CookieContainer cc = new CookieContainer();
            cc = addCookieToContainer(cookie, cc, domain);
            HttpClientHandler handler = new HttpClientHandler();
            handler.UseCookies = true;
            handler.CookieContainer = cc;
            httpClient = new HttpClient(handler);
        }

        public CookieContainer addCookieToContainer(string cookie, CookieContainer cc, string domain)
        {
            cookie = cookie.Replace(",", "%2C");//C# cookie不识别“,”
            string[] tempCookies = cookie.Split(';');
            string tempCookie = null;
            int Equallength = 0;//  =的位置 
            string cookieKey = null;
            string cookieValue = null;
            for (int i = 0; i < tempCookies.Length; i++)
            {
                if (!string.IsNullOrEmpty(tempCookies[i]))
                {
                    tempCookie = tempCookies[i];
                    Equallength = tempCookie.IndexOf("=");
                    if (Equallength != -1)       //有可能cookie 无=，就直接一个cookiename；比如:a=3;ck;abc=; 
                    {
                        cookieKey = tempCookie.Substring(0, Equallength).Trim();
                        //cookie= 
                        if (Equallength == tempCookie.Length - 1)    //这种是等号后面无值，如：abc=; 
                        {
                            cookieValue = "";
                        }
                        else
                        {
                            cookieValue = tempCookie.Substring(Equallength + 1, tempCookie.Length - Equallength - 1).Trim();
                        }
                    }
                    else
                    {
                        cookieKey = tempCookie.Trim();
                        cookieValue = "";
                    }
                    cc.Add(new Cookie(cookieKey, cookieValue, "", domain));
                }
            }
            return cc;
        }

        /// <summary>
        /// 下载文件到指定的目录
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="filePath">文件夹路径</param>
        /// <returns>文件名</returns>
        public string DownloadFileToDisk(string url, string filePath = "d:\\AspnetDownload")
        {
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);
            string fileName = Path.GetFileName(url);
            fileName = fileName.Length > 50 ? Path.GetRandomFileName() : fileName;
            while (File.Exists(Path.Combine(filePath, fileName)))
                fileName = Path.GetRandomFileName();
            webclient.DownloadFile(url, Path.Combine(filePath, fileName));
            return fileName;
        }
    }
}